package com.situ.springboot.controller;

import com.situ.springboot.pojo.Type;
import com.situ.springboot.service.ITypeService;
import com.situ.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/type")
public class TypeController {
    @Autowired
    private ITypeService typeService;
    @Autowired
    private RedisTemplate redisTemplate;

    //使用Map实现缓存
    //缺点：1、在内存里面，重启就销毁  2、只能在单机下面有效，无法实现分布式环境下缓存
    //private Map<String, Object> map = new HashMap<String, Object>();
    private Map<String, List<Type>> map = new HashMap<String, List<Type>>();

    @RequestMapping("/list2")
    public Result list2() {
        //1.首先查询Map缓存
        //List<Type> list = (List<Type>) map.get("typeList");
        List<Type> list = map.get("typeList");
        //2.Map中没有
        if (ObjectUtils.isEmpty(list)) {
            //3.查询数据库
            list = typeService.list();
            //4.从数据库查询出来之后，更新到缓存中
            map.put("typeList", list);
        }
        return Result.ok(list);
    }

    @RequestMapping("/list")
    public Result list() {
        //1.首先查询Redis缓存
        List<Type> list = redisTemplate.opsForList().range("typeList", 0, -1);
        //2.Redis中没有
        if (ObjectUtils.isEmpty(list)) {
            //3.查询数据库
            list = typeService.list();
            //4.从数据库查询出来之后，更新到缓存中
            redisTemplate.opsForList().rightPushAll("typeList", list);
        }
        return Result.ok(list);
    }
}
